<template>
  <div class='container'>
    <el-card class="box-card">
      <!-- 筛选区域 -->
      <!-- 按钮区域 -->
      <el-row>
        <el-col :span="12" style="color: red">
          说明:目前只支持学科和关键字条件筛选
        </el-col>
        <el-col :span="12">
          <el-button type="success" class="elBtn" @click="choiceAdd">
            <i class="el-icon-edit"></i> &nbsp;新增试题
          </el-button>
        </el-col>
      </el-row>
      <!-- 表单区域 -->
      <el-form ref="form" label-width="80px" :model="upForm">
        <!-- 第一行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科">
              <el-select v-model="upForm.subjectValue" placeholder="请选择" @change='subject'>
                <el-option :label="item.label" v-for="item in upForm.subjectForm" :key="item.value" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级目录">
              <el-select placeholder="请选择" v-model="upForm.twoLevelDirectoryValue">
                <el-option :label="item.label" v-for="item in upForm.twoLevelDirectoryForm" :key="item.value" :value="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签">
              <el-select placeholder="请选择" v-model="upForm.tagsValue">
                <el-option :label="item.label" v-for="item in upForm.tagsForm" :key="item.value" :value='item.label'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字">
              <el-input v-model="upForm.keyword"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="试题类型">
              <el-select placeholder="请选择" v-model="upForm.questionTypeValue">
                <el-option :label="item.label" :value="item.value" v-for="item in upForm.questionType" :key='item.value'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="难度">
              <el-select placeholder="请选择" v-model="upForm.difficultyValue">
                <el-option :label="item.label" :value="item.value" v-for="item in upForm.difficulty" :key='item.value'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方向">
              <el-select placeholder="请选择" v-model="upForm.directionValue">
                <el-option :label="item" :value="item" v-for="item in upForm.direction" :key='item'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入人">
              <el-select placeholder="请选择" v-model="upForm.creatorIDValue">
                <el-option :label="item.username" :value="item" v-for="item in upForm.creatorID" :key='item.id'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="题目备注">
              <el-input v-model="upForm.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业简称">
              <el-input v-model="upForm.shortName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市">
              <el-row>
                <el-col :span='12'>
                  <el-select placeholder="请选择" v-model="upForm.provincesValue" @change="provincesEvent">
                    <el-option :label="item" :value="item" v-for="item in upForm.provincesForm" :key="item.index"></el-option>
                  </el-select>
                </el-col>
                <el-col :span='12'>
                  <el-select placeholder="请选择" v-model="upForm.citysValue">
                    <el-option :label="item" :value="item" v-for="item in upForm.citysForm" :key="item.index"></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item style="float:right">
              <el-button @click="resetForm">清除</el-button>
              <el-button type="primary" @click="seachForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 列表区域 -->
      <!-- 提示区域 -->
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple-light"><i class=" el-icon-warning"></i> &nbsp;数据一共{{downForm.counts}}条</div>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table :data="downForm.tableData" border style="width: 100%">
        <el-table-column prop='number' label="试题编号" />
        <el-table-column prop='subject' label="学科" />
        <el-table-column prop='catalog' label="目录" />
        <el-table-column prop='questionType' label="题型" :formatter="questionTypeRester" />
        <el-table-column prop='question' label="题干">
          <template v-slot='{row}'>
            <p v-html="(row.question)">

            </p>
          </template>
        </el-table-column>
        <el-table-column prop='addDate' label="录入时间"><template v-slot="{ row }">
            {{ row.addDate | formatTime }}
          </template> </el-table-column>
        <el-table-column prop='difficulty' label="难度" :formatter="difficultyRester" />
        <el-table-column prop='creator' label="录入人" />
        <el-table-column prop='right' label="操作" sortable="" fixed="right" width="280">
          <template v-slot="{ row }">
            <el-button type="primary" plain size="small" @click="preview(row.id)"><i class="el-icon-view"></i></el-button>
            <el-button type="success" plain size="small" @click="$router.push('/questions/new?id='+ row.id)"><i class="el-icon-edit"></i></el-button>
            <el-button type="danger" plain size="small" @click="del(row)"><i class="el-icon-delete"></i></el-button>
            <el-button type="warning" plain size="small" @click="add(row)"><i class="el-icon-check"></i></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination style="margin-top: 20px; text-align: right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[1, 2, 3, 4]" :page-size="pagesize"
        layout="sizes, prev, pager, next, jumper" :total="downForm.count">
      </el-pagination>
    </el-card>
    <!-- 预览对话框 -->
    <el-dialog title="题目预览" :visible.sync="dialogVisible" width="70%" :before-close="handleClose">
      <el-row>
        <el-col :span="6">【题型】：{{questionTypeRester(detailQuestions)}}</el-col>
        <el-col :span="6">【编号】：{{detailQuestions.number}}</el-col>
        <el-col :span="6">【难度】：{{difficultyRester(detailQuestions)}}</el-col>
        <el-col :span="6">【标签】：{{detailQuestions.tags}}</el-col>
      </el-row>
      <el-row>
        <el-col :span="6">【学科】：{{detailQuestions.subjectName}}</el-col>
        <el-col :span="6">【目录】：{{detailQuestions.directoryName}}</el-col>
        <el-col :span="12">【方向】：{{detailQuestions.direction}}</el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">【题干】：</el-col>
      </el-row>
      <el-row>
        <el-col :span="24" v-html="detailQuestions.question"></el-col>
      </el-row>
      <el-row>
        <el-col :span="24">选项：（以下选中的选项为正确答案）</el-col>
      </el-row>
      <el-row v-for="item in detailQuestions.options" :key="item.id">
        <el-col :span="24">
          <el-radio v-model="radio" :label="item.id">{{item.code}}&nbsp;&nbsp;{{item.title}}</el-radio>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">【参考答案】：<el-button type="danger" @click="videoBtn">视频答案预览</el-button>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">【答案解析】：<i v-html="detailQuestions.answer"></i></el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="24">【题目备注】：{{detailQuestions.remarks}}）</el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 审核对话框 -->
    <el-dialog title="题目审核" width="20%" :visible.sync="dialogTableVisible">
      <el-radio v-model="auditRadio" label="1" name="1">通过</el-radio>
      <el-radio v-model="auditRadio" label="2" name="1">拒绝</el-radio>
      <el-input type="textarea" placeholder="请输入审核意见" v-model="text" maxlength="10" show-word-limit style="margin-top:36px"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 认</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
// 学科
import { simple as subjectsimple } from '@/api/hmmm/subjects.js'
import { simple as tagsSimple } from '@/api/hmmm/tags.js'
import { simple as directorysSimple } from '@/api/hmmm/directorys.js'
import { simple as UsersSimple } from '@/api/base/users.js'
import { questionType, difficulty, direction, chkType, publishType } from '@/api/hmmm/constants.js'
import { citys, provinces } from '@/api/hmmm/citys.js'
import { detail, choicePublish, list, remove, choiceAdd } from '@/api/hmmm/questions.js'

import dayjs from 'dayjs'
export default {
  // QuestionsChoice
  name: 'BaseQuestions',
  data () {
    return {
      // 加入精选题库
      row: {
        choiceState: 1,
        id: ''
      },
      // 筛选区域表单数据
      upForm: {
        // 学科简单列表数据
        subjectForm: [],
        // 学科简单列表选中值
        subjectValue: '',
        // 学科二级目录列表数据
        twoLevelDirectoryForm: [],
        // 学科二级目录列表选中值
        twoLevelDirectoryValue: '',
        // 标签列表
        tagsForm: '',
        // 标签选中值
        tagsValue: '',
        // 试题类型
        questionTypeValue: '',
        questionType,
        // 困难
        difficultyValue: '',
        difficulty,
        // 方向
        directionValue: '',
        direction,
        // 录入人
        creatorIDValue: '',
        creatorID: '',
        // 所有城市
        provincesForm: '',
        provincesValue: '',
        // 所有城市下地区信息
        citysForm: '',
        citysValue: '',
        // 关键字
        keyword: '',
        // 题目备注
        remarks: '',
        // 企业简称
        shortName: ''
      },
      // 选项卡数据
      activeName: 'first',
      // 列表区域表单数据
      downForm: {
        // 列表区域表单总数据
        tableData: [],
        // 列表区域表单数据总记录数
        counts: 0,
        // 审核状态
        chkState: ''
      },
      // 分页区域
      // 当前页
      currentPage: 1,
      // 每页几条数据
      pagesize: 4,
      // 预览对话框显示和隐藏
      dialogVisible: false,
      // 预览对话框显示信息
      detailQuestions: [{
        questionType: '', // 题型
        number: 0, // 编号
        difficulty: '', // 难度
        tags: '', // 试题标签
        subjectName: '', // 学科
        directoryName: '', // 目录
        direction: '', // 方向
        question: '', // 题干
        options: '', // 选项
        videoURL: '', // 解析视频
        answerID: '', // 答案解析
        remarks: ''// 题目备注
      }],
      // 题干答案默认选中
      radio: 109,
      // 审核对话框显示信息
      dialogTableVisible: false,
      // 审核选项默认选中
      auditRadio: 1,
      // 审核选项输入框内容
      text: ''
    }
  },
  created () {
    this.subjectSimple()
    this.initQuestionList()
    this.getProvinces()
  },
  methods: {
    // 动态控制索引
    handleIndex (index) {
      // 当前页前面的页数 * 每页条数 + index + 1
      const { page, pagesize } = this.pagesize
      return (page - 1) * pagesize + index + 1
    },
    // 新增学科
    choiceAdd () {
      console.log(this.$router)
      this.$router.push('/questions/new')
    },
    // 初始化时触发的事件,获取学科一级目录,录入人
    async subjectSimple () {
      const res = await subjectsimple()
      const ret = await UsersSimple()
      this.upForm.subjectForm = res.data
      this.upForm.creatorID = ret.data
    },
    // 一级目录下拉框选中值触发的事件
    async subject () {
      // 获取二级目录学科详情、标签(需要学科一级目录ID)
      this.upForm.twoLevelDirectoryValue = ''
      this.upForm.tagsValue = ''
      const res = await tagsSimple(
        { subjectID: this.upForm.subjectValue }
      )
      const ret = await directorysSimple({ subjectID: this.upForm.subjectValue })
      this.upForm.twoLevelDirectoryForm = res.data
      this.upForm.tagsForm = ret.data
    },
    // 清除筛选区域表单
    resetForm () {
      this.upForm = this.$options.data().upForm
      // 刷新页面
      this.initQuestionList()
      this.subjectSimple()
      this.getProvinces()
    },
    // 根据筛选区域获取展示列表
    async seachForm () {
      this.pagesize = 100
      const oldObject = {
        page: this.currentPage,
        pagesize: this.pagesize,
        subjectID: this.upForm.subjectValue,
        difficulty: this.upForm.difficultyValue,
        questionType: this.upForm.questionTypeValue,
        tags: this.upForm.tagsValue,
        province: this.upForm.provinceValue,
        city: this.upForm.cityValue,
        keyword: this.upForm.keyword,
        remarks: this.upForm.remarks,
        shortName: this.upForm.shortName,
        direction: this.upForm.directionValue,
        creatorID: this.upForm.creatorIDValue,
        catalogID: this.upForm.twoLevelDirectoryValue
      }
      const newObject = {}
      for (const key in oldObject) {
        if (oldObject[key]) {
          newObject[key] = oldObject[key]
        }
      }
      const res = await list(newObject)
      this.downForm.tableData = res.data.items
      this.downForm.counts = res.data.counts
      // this.downForm.chkState = ''
    },
    // 获取所有城市信息（把导入到方法当作接口使用）
    getProvinces () {
      const res = provinces()
      this.upForm.provincesForm = res
    },
    // 获取所有城市下属地区信息
    provincesEvent () {
      this.upForm.citysValue = ''
      const res = citys(this.upForm.provincesValue)
      this.upForm.citysForm = res
      console.log(res)
    },
    // 列表区域数据格式化
    // 题型数据格式化
    questionTypeRester (val) {
      const res = questionType.find(item => {
        return item.value === Number(val.questionType)
      })
      return res ? res.label : '---'
    },
    // 对时间进行格式化
    addDateRester (val) {
      return dayjs(val.addDate).format('YYYY-MM-DD')
    },
    // 对难度进行格式化
    difficultyRester (val) {
      const res = difficulty.find(item => item.value === Number(val.difficulty))
      return res ? res.label : '---'
    },
    // 对审核状态进行格式化
    chkStateRester (val) {
      const res = chkType.find(item => item.value === (val.chkState + 1))
      return res.label
    },
    // 对发布状态进行格式化
    publishStateRester (val) {
      const res = publishType.find(item => item.value === (val.chkState + 1))
      return res.label
    },

    // 每页条数改变时触发
    handleSizeChange (page) {
      this.pagesize = page
    },
    // 当前页条数改变时触发
    async handleCurrentChange (page) {
      this.currentPage = page
    },
    // 操作预览
    async preview (id) {
      this.dialogVisible = true
      const res = await detail({ id })
      this.detailQuestions = res.data
    },
    // 操作审核
    async audit (id) {
      this.dialogTableVisible = true
      const res = await detail({ id })
      this.auditRadio = res.data.chkState
      this.text = res.data.chkRemarks
    },
    // 操作修改
    modify (id) { },
    // 操作上架
    shelves (id) {
      this.$confirm('此操作将更改该试题, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ret = await choicePublish({ id, publishState: 1 })
        if (ret.code === 200) {
          this.$message.success('上架成功')
        }
      }).catch(() => { })
    },
    // (查)
    async initQuestionList () {
      try {
        const ret = await list(this.requestParameters)
        if (ret.status === 200) {
          this.downForm.tableData = ret.data.items
          this.downForm.counts = ret.data.counts
          // this.total = ret.data.counts
        } else {
          this.$message.error('获取学科列表失败!')
        }
      } catch (error) {
        console.log(error)
        this.$message.error('获取学科列表失败!')
      }
    },
    // 操作删除
    // (删)
    async del (row) {
      const isOk = await this.$confirm('确认要删除该试题吗？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 点击取消操作
      if (isOk === 'cancel') return

      // 点击确定操作进行删除
      try {
        const ret = await remove(row)
        console.log(ret)
        if (ret.status === 200) {
          console.log(ret)
          // 删除成功，刷新列表
          this.initQuestionList()
        } else {
          this.$message.error('删除失败')
        }
      } catch (error) {
        console.log(error)
        this.$message.error('删除失败')
      }
    },

    // 预览对话框
    handleClose () {
      this.dialogVisible = false
    },
    // 视频答案解析
    videoBtn () { },
    // 加入精选题库
    async add (row) {
      const isOk = await this.$confirm('此操作将该题目加入精选, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 点击取消操作
      if (isOk === 'cancel') return
      // 点击确定操作进行加入精选题库

      try {
        const ret = await choiceAdd({ id: row.id, choiceState: 1 })
        console.log(ret)
        if (ret.status === 200) {
          console.log(ret)
          this.$message.success('添加精选题库成功')
          // 添加成功，刷新列表
          this.initQuestionList()
        } else {
          this.$message.error('添加失败')
        }
      } catch (error) {
        console.log(error)
        this.$message.error('添加失败')
      }
    }
  }
}

</script>

<style scoped lang='scss'>
.box-card {
  margin-left: 10px;
  margin-right: 10px;
  .elBtn {
    float: right;
    margin: 18px;
    margin-top: 0;
  }
  .bg-purple-light {
    background: #f4f4f5;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    line-height: 36px;
    padding-left: 20px;
    color: #909fc0;
    font-size: 14px;
  }
}
</style>
